/**
 * @author Jaanus Jaggo
 */
var p = new Player();

function updateCamera() {
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	camera.x = (-p.x - grid / 2) * camera.scale + canvas.width/2;
	camera.y = (-p.y - grid / 2) * camera.scale + canvas.height/2;
	//camera.x = -p.x;
	//camera.y = -p.y;
	ctx.setTransform(camera.scale, 0, 0, camera.scale, camera.x, camera.y);
}

function update() {
	p.update();
	updateCamera();
	updateArrowKeys();
	//Game logic goes here
}

function updateArrowKeys() {
	/*
	if (17 in keys && keys[17]) { //ctrl
		alert("CTRL");
		canvasLostFocus();
	}*/
	if (38 in keys && keys[38] || (87 in keys && keys[87])) { //up
		if (!p.isMoving()) {
			//if (isPlaceFree(p.getPosX(), p.getPosY() - 1)) {
				p.moveY(-10);
			//}
		}
	}
	if ((39 in keys && keys[39]) || (68 in keys && keys[68])) { //right
		if (!p.isMoving()) {
			//if (isPlaceFree(p.getPosX() + 1, p.getPosY())) {
				p.moveX(10);
			//}
		}
	}
	if ((40 in keys && keys[40]) || (83 in keys && keys[83])) { //down
		if (!p.isMoving()) {
			//if (isPlaceFree(p.getPosX(), p.getPosY() + 1)) {
				p.moveY(10);
			//}
		}
	}
	if (37 in keys && keys[37] || (65 in keys && keys[65])) { //left
		if (!p.isMoving()) {
			//alert(isPlaceFree(p.getPosX(), p.getPosY()));
			//if (isPlaceFree(p.getPosX() - 1, p.getPosY())) {
				p.moveX(-10);
			//}
		}
	}
}

function draw() {
	//Draw everything here
	drawBackground();
	p.draw();
	drawHud();
}

function drawHud() {
	ctx.save(); //Saving current transformation matrix
	ctx.setTransform(1, 0, 0, 1, 0, 0);
	//draw FPS
	ctx.fillStyle = "#000";
	ctx.font = "bold 12px sans-serif";
  	ctx.fillText("fps: " + Math.min(curFPS, maxFPS) + "/" + maxFPS, 10, 20);
  	++numFramesDrawn;
	
	ctx.restore();
}